package com.ifacebox.vcam4j;

import java.awt.Graphics;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.awt.image.DataBufferByte;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import javax.imageio.ImageIO;

/**
 * @author znn
 */
public abstract class VCamService {
    public static final int VCAM_S_OK = 0;
    public static final int VCAM_MIN_FPS = 10;
    public static final int VCAM_FPS = 100;
    public static final int VCAM_MAX_FPS = 1000;
    public static final int VCAM_WIDTH = 640;
    public static final int VCAM_HEIGHT = 480;

    /**
     * @return
     */
    public abstract String getName();

    /**
     * 检查设备是否正被其他应用程序使用。
     *
     * @return
     */
    public abstract boolean isOpened();

    /**
     * 向驱动程序发送 RGB24 格式的视频缓冲区。
     *
     * @param data
     */
    public abstract void sendFrameEx(byte[] data);

    /**
     * 开始屏幕捕获，鼠标跟踪捕获。
     */
    public abstract void captureScreen();

    /**
     * 屏幕捕获。
     *
     * @param x
     * @param y
     * @param width
     * @param height
     */
    public abstract void captureScreen(int x, int y, int width, int height);

    /**
     * 停止屏幕捕获。
     */
    public abstract void stopCaptureScreen();

    /**
     * 销毁。
     */
    public abstract void dispose();

    public void sleepFps(int fps) {
        try {
            Thread.sleep(fps <= VCAM_MAX_FPS && fps >= VCAM_MIN_FPS ? fps : VCAM_FPS);
        } catch (Exception e) {
            //
        }
    }

    public byte[] getFrameEx(byte[] data) {
        try {
            BufferedImage bufferedImage = new BufferedImage(VCAM_WIDTH, VCAM_HEIGHT, BufferedImage.TYPE_3BYTE_BGR);
            Graphics graphics = bufferedImage.getGraphics();
            try (ByteArrayInputStream inputStream = new ByteArrayInputStream(data)) {
                Image image = ImageIO.read(inputStream);
                if (image.getWidth(null) != VCAM_WIDTH || image.getHeight(null) != VCAM_HEIGHT) {
                    image = image.getScaledInstance(VCAM_WIDTH, VCAM_HEIGHT, Image.SCALE_FAST);
                }
                graphics.drawImage(image, 0, 0, VCAM_WIDTH, VCAM_HEIGHT, 0, VCAM_HEIGHT, VCAM_WIDTH, 0, null);
            } finally {
                graphics.dispose();
            }
            return ((DataBufferByte) bufferedImage.getRaster().getDataBuffer()).getData();
        } catch (IOException e) {
            return new byte[0];
        }
    }
}
